import React, { Component } from 'react';
import {
  Form,
  Input,
  Button,
  Select,
  Row,
  Col,
  Popover,
  Progress,
  Card,
  AutoComplete,
  Icon,
} from 'antd';
import { requestLists, requestPromise } from '@/utils/request';
import styles from './Resetpassword.less';
import { getWebPath } from '../../utils/request';
import uiUtils, { rulesReg, rulesRemote } from '../../utils/uiUtils';

const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;
@Form.create()
class Resetpassword extends Component {
  mailSuffix = ['163.com', '126.com', 'gmail.com', 'qq.com', 'hotmail.com', 'sohu.com', 'sina.com'];

  state = {
    isAvailable: 3,
    mailDataSource: [],
    src: getWebPath(`/captcha.jpg?t=${Math.random()}`),
    isShowPasswordEmailBtn: true,
  };

  componentDidMount() {
    this.queryIsAvailable();
  }

  queryIsAvailable = () => {
    //获取参数
    if (this.props.location.query !== undefined) {
      if (this.props.location.query.param !== undefined) {
        const url = `sys/user/queryResetPwdTimeIsAvailable`;
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: { param: this.props.location.query.param },
          contentType: 'application/x-www-form-urlencoded',
        }).then(res => {
          if (res.code === 0) {
            this.setState({
              isAvailable: res.obj.isAvailable,
            });
          }
        });
      }
    }
  };

  resetPassword = () => {
    const user = {
      password: this.props.form.getFieldValue('password'),
      param: this.props.location.query.param,
    };
    this.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-prototype-builtins
      if (!err) {
        this.setState({ resetLoading: true });
        const url = '/sys/user/resetNewPassword';
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: user,
          contentType: 'application/x-www-form-urlencoded',
        }).then(res => {
          this.setState({
            resetLoading: false,
          });
          if (res && res.code === 0) {
            // uiUtils.showMessage(res.msg,'success');
            // eslint-disable-next-line no-restricted-globals
            window.location.href = `${location.protocol}//${location.host}${
              location.pathname
            }#/user/login`;
          }
        });
      }
    });
  };

  onGetImgCaptcha = () => {
    this.setState({
      src: getWebPath(`/captcha.jpg?t=${Math.random()}`),
    });
  };

  sendPasswordEmail = () => {
    // eslint-disable-next-line no-restricted-globals
    const resetPwdUrl = `${location.protocol}//${location.host}${
      location.pathname
    }#/user/reset-password`;
    const user = {
      username: this.props.form.getFieldValue('username'),
      email: this.props.form.getFieldValue('email'),
      code: this.props.form.getFieldValue('code'),
      url: resetPwdUrl,
    };
    this.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-prototype-builtins
      if (!err) {
        this.setState({ loading: true });
        const url = '/sys/user/sendResetPasswordEmail';
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: user,
          contentType: 'application/x-www-form-urlencoded',
        }).then(res => {
          this.setState({
            loading: false,
          });
          if (res && res.code === 0) {
            this.setState({
              isShowPasswordEmailBtn: false,
            });
          }
        });
      }
    });
  };

  autoCompleteHandleSearch = value => {
    this.setState({
      mailDataSource:
        !value || value.indexOf('@') === -1
          ? []
          : this.mailSuffix
              .map(en => `${value.split('@', 2)[0]}@${en}`)
              .filter(en => en.indexOf(value.split('@', 2)[1]) !== -1),
    });
  };

  render() {
    const colSpanLayout = { md: 21, sm: 21 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之间的间隔?px
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 17 }, //5+19=24,少一个栅格
    };
    const { getFieldDecorator } = this.props.form;

    return (
      <Card
        title={this.state.isAvailable === 1 ? '链接已过期' : '重置密码'}
        className={styles.cardBody}
      >
        {this.state.isAvailable === 3 && (
          <div>
            <Form layout="horizontal">
              <Row gutter={{ ...rowGutterPxLayout }} style={{ width: 500, float: 'left' }}>
                <Col {...colSpanLayout}>
                  <FormItem label="用户名：" {...formItemLayout}>
                    {getFieldDecorator('username', {
                      rules: [
                        {
                          required: true,
                          message: '必填',
                        },
                      ],
                    })(<Input type="text" autocomplete="off" placeholder="用户名" />)}
                  </FormItem>
                </Col>
                <Col {...colSpanLayout}>
                  <FormItem label="邮箱：" {...formItemLayout}>
                    {getFieldDecorator('email', {
                      rules: [
                        {
                          required: true,
                          message: '必填',
                        },
                        rulesReg('email'),
                      ],
                    })(
                      <AutoComplete
                        type="text"
                        maxLength={50}
                        placeholder=""
                        autocomplete="off"
                        dataSource={this.state.mailDataSource}
                        onSearch={this.autoCompleteHandleSearch}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colSpanLayout}>
                  <FormItem label="验证码：" {...formItemLayout}>
                    {getFieldDecorator('code', {
                      rules: [
                        {
                          required: true,
                          message: '必填',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        maxLength={10}
                        placeholder=""
                        style={{ width: 100 }}
                        autocomplete="off"
                      />
                    )}
                    {/* eslint-disable-next-line jsx-a11y/alt-text */}
                    <img
                      src={this.state.src}
                      onClick={this.onGetImgCaptcha}
                      style={{ float: 'right', width: 150, height: 32 }}
                    />
                  </FormItem>
                </Col>
                <Col {...colSpanLayout}>
                  <p className={styles.codeInfo}>验证码，点击图片可更换</p>
                </Col>

                <Col {...colSpanLayout}>
                  {this.state.isShowPasswordEmailBtn === true && (
                    <Button
                      type="primary"
                      loading={this.state.loading}
                      onClick={this.sendPasswordEmail}
                      style={{ width: '100%' }}
                    >
                      发送密码重置确认函
                    </Button>
                  )}
                  {this.state.isShowPasswordEmailBtn === false && (
                    <div className={styles.successInfo}>密码重置确认函已发送，请注意查收！</div>
                  )}
                </Col>
              </Row>
              <Col class="col-md-7">
                <div className={styles.alertInfo}>
                  <p>请填写用户信息，随后一封密码重置确认函将发送到您的邮箱。</p>
                  <p>请注意，密码重置确认函在24小时内有效！</p>
                  <p>&nbsp;</p>
                  <p>如果您的用户账号没有设置关联邮箱，请联系系统管理员为您重置密码。</p>
                </div>
              </Col>
            </Form>
          </div>
        )}
        {this.state.isAvailable === 2 && (
          <div className={styles.cardCenter}>
            <Form layout="horizontal">
              <Row gutter={{ ...rowGutterPxLayout }} style={{ width: 500 }}>
                <Col {...colSpanLayout}>
                  <FormItem label="新密码：" {...formItemLayout}>
                    {getFieldDecorator('password', {
                      rules: [
                        {
                          required: true,
                          message: '必填',
                        },
                        {
                          min: 6,
                          message: '密码最少6位',
                        },
                      ],
                    })(<Input.Password type="text" maxLength={50} placeholder="新密码" />)}
                  </FormItem>
                </Col>
                <Button
                  type="primary"
                  loading={this.state.resetLoading}
                  onClick={this.resetPassword}
                  style={{ padding: '0 140px', margin: '0 50px' }}
                  icon="check"
                >
                  重置密码
                </Button>
              </Row>
            </Form>
          </div>
        )}
        {this.state.isAvailable === 1 && (
          <div>
            <div className={styles.alertDanger}>
              当前使用的密码重置链接已经过期！密码重置链接仅在24小时内有效，请及时设置您的新密码！
            </div>
            <div>
              您可以：
              <ul>
                <li>联系管理员手工重置密码</li>
                <li>
                  <a
                    onClick={() => {
                      this.setState({
                        isAvailable: 3,
                      });
                    }}
                  >
                    重新重置密码
                  </a>
                </li>
              </ul>
            </div>
          </div>
        )}
      </Card>
    );
  }
}

export default Resetpassword;
